package com.p2p.backend.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.p2p.backend.service.BackUserService;
import com.p2p.backend.service.OplogService;
import com.p2p.backend.util.PageUtils;
import com.p2p.base.annotation.PermissionNeed;
import com.p2p.base.model.Action;
import com.p2p.base.model.Module;
import com.p2p.base.model.Oplog;
import com.p2p.base.page.PageVo;
import com.p2p.base.util.MD5Util;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.dao.UserDao;
import com.p2p.front.dal.model.User;
import com.p2p.front.enums.UserCreditsType;
import com.p2p.front.service.UserCreditsService;
import com.p2p.front.service.UserInfoService;
import com.p2p.front.service.UserSequenceService;
import com.p2p.front.service.UserService;
import com.p2p.front.util.BorrowerAuthUtil;
import com.p2p.trans.client.facade.AccountOpenFacade;
import com.p2p.trans.client.result.AccountOpenResult;
import com.p2p.user.enums.UserInfoName;

/**
 * leiwen@yiqihao.com
 */
@RequestMapping("borrower")
@Controller
public class BorrowerController extends BaseController{

	@Resource
	private BackUserService backUserService;

	@Resource
	private UserService userService;
	@Resource
	private UserSequenceService userSequenceService;

	@Resource
	private UserInfoService userInfoService;

	@Resource
	private UserDao userDao;

	@Resource
	private AccountOpenFacade remotAccountOpenFacade;
	
	@Resource
	private UserCreditsService userCreditsService;

	Logger log = Logger.getLogger(this.getClass());

	@PermissionNeed("borrower_list")
	@RequestMapping("list")
	public void list(PageVo vo, Model model) {
		log.info("borrower_list"+vo.getSearch());
		vo.handleSearch();
		PageVo page = backUserService.list(vo);
		model.addAttribute("res", 1);
		model.addAttribute("data", PageUtils.data(page));
	}

	@PermissionNeed("borrower_management")
	@RequestMapping("auth")
	public String auth(Long uid, Model model) {
		Map<String, Object> borrowerAuth = userInfoService.getOne(String.valueOf(uid),UserInfoName.BORROWER_AUTH);
		Map<String, Object> auth = BorrowerAuthUtil.authToParams(MapUtils
				.getString(borrowerAuth, "info_value"));
		model.addAllAttributes(auth);
		model.addAttribute("user_id", uid);
		return "borrower/auth";
	}

	@PermissionNeed("borrower_management")
	@RequestMapping("updateauth")
	public String updateauth(@RequestParam Map<String, Object> params,
			Model model, HttpServletRequest request) {
		String auth = BorrowerAuthUtil.paramsToAuth(params);
		String uid = MapUtils.getString(params, "uid");
		if (uid == null) {
			log.error("uid is null whene update auth");
		}
		userInfoService.updateOne(uid,UserInfoName.BORROWER_AUTH, auth);
		Oplog oplog = super.oplog(request);
		oplog.setModule(Module.BORROWER_USER);
		oplog.setAction(Action.UPDATE);
		oplog.setParams(ToStringBuilder.reflectionToString(params));
		OplogService.log(oplog);
		return "borrower/auth";
	}

	@PermissionNeed("borrower_management")
	@RequestMapping("update")
	public String update(Integer uid, Model model) {
		Map<String, Object> user = backUserService.get(uid);
		model.addAttribute("user", user);
		return "borrower/update";
	}

	@PermissionNeed("borrower_management")
	@RequestMapping("doadd")
	public void doadd(@RequestParam Map<String, Object> params, Model model, HttpServletRequest request) {
		String uid = userSequenceService.getNextBorrowerUserId();
		params.put("uid", uid);
		sha1Password(params);
		log.info("creat borrow user name="+params.get("uname"));
		boolean result = backUserService.add(params);
		if(!result){
			model.addAttribute("res", 0);
			return;
		}
		AccountOpenResult accountOpenResult = remotAccountOpenFacade
				.openAccountForUser(uid, new HashMap<String, Object>());
		if (accountOpenResult.isSuccess()) {
			
			String accountNo = accountOpenResult.getAccountNo();
			params.put("accountNo", accountNo);
			
			
			User user = new User();
			user.setUid(uid);
			user.setAccountNo(accountNo);
			userDao.updateAccountNo(user);
			userCreditsService.create(uid, UserCreditsType.UserCreditsNeedCharge, 0l);
			userInfoService.updateOne(uid, UserInfoName.BORROWER_AUTH, BorrowerAuthUtil.getDefaultValue());
			model.addAttribute("res", 1);
		} else {
			model.addAttribute("res", 0);
			return;
		}
		Oplog oplog = super.oplog(request);
		oplog.setModule(Module.BORROWER_USER);
		oplog.setAction(Action.ADD);
		oplog.setParams(ToStringBuilder.reflectionToString(params));
		OplogService.log(oplog);
	}

	@PermissionNeed("borrower_management")
	@RequestMapping("doupdate")
	public void doupate(@RequestParam Map<String, Object> params, Model model, HttpServletRequest request) {
		sha1Password(params);
		boolean result = backUserService.update(params);
		model.addAttribute("res", result?1:0);
		Oplog oplog = super.oplog(request);
		oplog.setModule(Module.BORROWER_USER);
		oplog.setAction(Action.UPDATE);
		oplog.setParams(ToStringBuilder.reflectionToString(params));
		OplogService.log(oplog);
	}

	private void sha1Password(Map<String, Object> params) {
		Object password = params.get("password");
		if (password == null) {
			log.error("password is null");
			return;
		}
		String md5Password = MD5Util.sha1(password.toString());
		params.put("password", md5Password);
	}
}
